package com.pro.springbootshop.advise;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pro.springbootshop.model.HttpResponse;
import com.pro.springbootshop.annotion.NoWapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;

//扫描要做统一返回项
@RestControllerAdvice(basePackages = {"com.pro.springbootshop.controller"})
public class MyResoonseBody implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //找到当前执行的方法属于哪个类
        Class<?> declaringClass = returnType.getDeclaringClass();
        //查找该类是否有NoWapper注解
        boolean b = AnnotationUtil.hasAnnotation(declaringClass, NoWapper.class);
        //如果有就不用再统一封装.
        if(b){
            return  false; //返回false就不会再进下面beforeBodyWrite方法.
        }
        return true;//所有都拦截
    }
    //处理异常
    @ExceptionHandler(value = Exception.class)
    public Object defaulErrorHander(HttpServletRequest req, Exception ex) {
        HttpResponse<Object> httpResponse = new HttpResponse<>();
        httpResponse.setCode(400);
        httpResponse.setMessage(ex.getMessage());
        return httpResponse;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        HttpResponse<Object> httpResponse = new HttpResponse<>();
        //hutool初始message转换为空
        String message = StrUtil.EMPTY;
        httpResponse.setCode(200);
        httpResponse.setMessage(message);
        httpResponse.setData(body);
        //处理返回类型为字符串
        if(selectedConverterType == StringHttpMessageConverter.class){
            //hutool JSONUtil.toJsonStr字符串转换为json数据
            return JSONUtil.toJsonStr(httpResponse);
        } else{
            return httpResponse;
        }
    }
}